import React, { useState } from 'react';
import { useAuthStore } from '@/stores/authStore';
import { messageService } from '@/services/messageService';
import { socketService } from '@/services/socketService';
import { toast } from 'react-hot-toast';

const DebugPanel: React.FC = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [testMessage, setTestMessage] = useState('测试消息');
  const { user, tokens } = useAuthStore();

  const handleTestMessageAPI = async () => {
    console.log('🧪 [DEBUG] 测试消息API...');
    try {
      const messages = await messageService.getMessages();
      console.log('✅ [DEBUG] 消息API测试成功:', messages);
      toast.success(`消息API测试成功，获取到 ${messages.length} 条消息`);
    } catch (error) {
      console.error('❌ [DEBUG] 消息API测试失败:', error);
      toast.error('消息API测试失败');
    }
  };

  const handleTestSocket = () => {
    console.log('🧪 [DEBUG] 测试Socket连接...');
    const isConnected = socketService.isConnected();
    console.log('🔌 [DEBUG] Socket连接状态:', isConnected);
    toast.success(`Socket连接状态: ${isConnected ? '已连接' : '未连接'}`);
  };

  const handleSendTestMessage = () => {
    console.log('🧪 [DEBUG] 发送测试消息...');
    if (!testMessage.trim()) {
      toast.error('请输入测试消息');
      return;
    }
    socketService.sendMessage(testMessage, 'text');
    toast.success('测试消息已发送');
  };

  const handleClearConsole = () => {
    console.clear();
    toast.success('控制台已清空');
  };

  const handleShowAuthInfo = () => {
    console.log('🔐 [DEBUG] 当前认证信息:', {
      hasUser: !!user,
      userId: user?.id,
      username: user?.username,
      userType: typeof user?.id,
      hasTokens: !!tokens,
      hasAccessToken: !!tokens?.accessToken,
      tokenLength: tokens?.accessToken?.length,
      fullUser: user
    });
    toast.success('认证信息已输出到控制台');
  };

  if (!isOpen) {
    return (
      <div className="fixed top-4 right-4 z-50">
        <button
          onClick={() => setIsOpen(true)}
          className="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg shadow-lg transition-colors"
        >
          🐛 调试面板
        </button>
      </div>
    );
  }

  return (
    <div className="fixed top-4 right-4 z-50 bg-white border border-gray-300 rounded-lg shadow-xl p-4 w-80">
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-lg font-semibold text-gray-800">🐛 调试面板</h3>
        <button
          onClick={() => setIsOpen(false)}
          className="text-gray-500 hover:text-gray-700 text-xl"
        >
          ×
        </button>
      </div>
      
      <div className="space-y-3">
        <div className="text-sm text-gray-600">
          <p>用户: {user?.username || '未登录'}</p>
          <p>Socket: {socketService.isConnected() ? '✅ 已连接' : '❌ 未连接'}</p>
        </div>
        
        <div className="space-y-2">
          <button
            onClick={handleShowAuthInfo}
            className="w-full bg-green-500 hover:bg-green-600 text-white px-3 py-2 rounded text-sm transition-colors"
          >
            📋 显示认证信息
          </button>
          
          <button
            onClick={handleTestMessageAPI}
            className="w-full bg-blue-500 hover:bg-blue-600 text-white px-3 py-2 rounded text-sm transition-colors"
          >
            📡 测试消息API
          </button>
          
          <button
            onClick={handleTestSocket}
            className="w-full bg-purple-500 hover:bg-purple-600 text-white px-3 py-2 rounded text-sm transition-colors"
          >
            🔌 测试Socket连接
          </button>
          
          <div className="flex space-x-2">
            <input
              type="text"
              value={testMessage}
              onChange={(e) => setTestMessage(e.target.value)}
              placeholder="测试消息内容"
              className="flex-1 px-2 py-1 border border-gray-300 rounded text-sm"
            />
            <button
              onClick={handleSendTestMessage}
              className="bg-orange-500 hover:bg-orange-600 text-white px-3 py-1 rounded text-sm transition-colors"
            >
              📤 发送
            </button>
          </div>
          
          <button
            onClick={() => {
              console.log('📊 [DEBUG] 当前消息数据:', window.messagesDebug || '无消息数据');
              toast.success('消息数据已输出到控制台');
            }}
            className="w-full bg-indigo-500 hover:bg-indigo-600 text-white px-3 py-2 rounded text-sm transition-colors"
          >
            📊 显示消息数据
          </button>
          
          <button
            onClick={handleClearConsole}
            className="w-full bg-gray-500 hover:bg-gray-600 text-white px-3 py-2 rounded text-sm transition-colors"
          >
            🧹 清空控制台
          </button>
        </div>
        
        <div className="text-xs text-gray-500 mt-3">
          💡 提示：打开浏览器控制台查看详细调试信息
        </div>
      </div>
    </div>
  );
};

export default DebugPanel;